<template>
  <view class="login-container">
    <uni-forms :modelValue="formData" :rules="rules" ref="formRef">
      <uni-forms-item label="姓名" required name="loginname">
        <uni-easyinput
          type="text"
          v-model="formData.loginname"
          placeholder="请输入姓名"
        />
      </uni-forms-item>
      <uni-forms-item label="密码" required name="password">
        <uni-easyinput
          type="password"
          v-model="formData.password"
          placeholder="请输入密码"
        />
      </uni-forms-item>
      <button @click="onLogin">登录</button>
    </uni-forms>
  </view>
</template>

<script setup lang="ts">
import { userLogin } from '@/api/user'
import {useUserInfo} from '@/store/user'
import { ref } from 'vue'

const store=useUserInfo()
const formRef = ref()
const formData = ref({
  loginname: '17704051019',
  password: '123456'
})
const rules = {
  loginname: {
    rules: [
      {
        required: true,
        errorMessage: '手机号不能为空！'
      },
      {
        pattern: /^1[3-9]\d{9}$/,
        errorMessage: '手机号不合法！'
      }
    ]
  },
  password: {
    rules: [
      {
        required: true,
        errorMessage: '密码不能为空！'
      },
      {
        pattern: /^\S{6,}$/,
        errorMessage: '密码至少6位！'
      }
    ]
  }
}
const onLogin = async () => {
  try {
    await formRef.value.validate()

    const res = await userLogin({
      loginname: formData.value.loginname,
      password: formData.value.password
    })
    if (res.code === 200) {
      store.setUserInfo(res.data.token)
      uni.showToast({
        icon: 'success',
        title: '登录成功',
        success: () => {
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/home/index'
            })
          }, 500)
        }
      })
    } else {
      uni.showToast({
        icon: 'none',
        title: '用户名或密码错误'
      })
    }
  } catch (error) {
    console.log(error)
  }
}
</script>

<style lang="less" scoped>
.login-container {
  padding: 20rpx;
  button {
    width: 90%;
    background-color: #c82519;
    color: #fff;
    border-radius: 25px;
  }
}
</style>
